﻿using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Puppy.Autofac.DynamicProxy;
using Puppy.Domain.Repositories;
using Puppy.Modularity;
using Puppy.Uow;

namespace Puppy.Internal
{
    internal static class InternalServiceCollectionExtensions
    {
        internal static void AddCoreServices(this IServiceCollection services)
        {
            services.AddOptions();
            services.AddLogging();
            services.AddLocalization();
        }

        internal static void AddCorePuppyServices(this IServiceCollection services, 
            IPuppyApplication puppyApplication, 
            PuppyApplicationOptions options)
        {
            var moduleLoader = new ModuleLoader();
            services.TryAddSingleton<IModuleLoader>(moduleLoader);

            services.AddAssemblyOf<IPuppyApplication>();
            services.AddConventionalRegistrar(new RepositoryConventionalRegistrar());

            services.Configure<ModuleLifecycleOptions>(options =>
            {
                options.Contributors.Add<OnPreApplicationInitializationModuleLifecycleContributor>();
                options.Contributors.Add<OnApplicationInitializationModuleLifecycleContributor>();
                options.Contributors.Add<OnPostApplicationInitializationModuleLifecycleContributor>();
                options.Contributors.Add<OnApplicationShutdownModuleLifecycleContributor>();
            });

            services.AddTransient(typeof(AsyncDeterminationInterceptor<>));
            services.OnRegistred(UnitOfWorkInterceptorRegistrar.RegisterIfNeeded);
        }
    }
}
